<?php


namespace app\common\model\mysql\system;


use app\common\exception\MessageException;
use app\common\model\mysql\BaseModel;
use think\model\concern\SoftDelete;

class User extends BaseModel
{
    use SoftDelete;

    protected $deleteTime = 'delete_time';

    // 定义主键 alter table users AUTO_INCREMENT=10000;
    protected $pk = 'id';

    // 设置当前模型对应的完整数据表名称
    protected $table = 'sys_user';

    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = true;

    // 模型初始化
    protected static function init()
    {
        // TODO:初始化内容
    }

    /**
     * 关联部门表
     * @return \think\model\relation\hasOne
     */
    public function department()
    {
        return $this->hasOne('Department', 'id', 'department_id')->bind(['department_name' => 'name']);
    }

    /**
     * 关联职位表
     * @return \think\model\relation\hasOne
     */
    public function post()
    {
        return $this->hasOne('Post', 'id', 'post_id')->bind(['post_name' => 'name']);
    }

    // 检查分类名是否存在
    public function checkName($name, $id = null)
    {
        if (!$name) {
            throw new MessageException(['msg' => '分类名不合法']);
        }

        // 设置查询条件
        // $condition = ['name' => $name];
        $data = $this->where('name', $name);
        if ($id) {
            $data = $data->where('id', '<>', $id);
        }

        return $data->find();
    }

}